const axios = require('axios').default;
const fs = require('fs');
const path = require('path');
const logger = require('./console-logger');

function doRequest(options) {
  logger.debug('doRequest options: ', options)
  options.url && (options.url = encodeURI(options.url))
  return new Promise((resolve, reject) => {
    axios(options)
      .then(function (response) {
        // console.log(response);
        if (response.status === 200) {
          resolve(response.data);
        } else {
          reject(new Error(`Request Failed,Status Code: ${response.status}`))
          // logger.error('doRequest error: ', `Request Failed,Status Code: ${response.status}`)
        }
      })
      .catch(function (error) {
        //   logger.error('doRequest error: ', error.message)
        reject(error);
      })
  });
}

function download(url, dest) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url: encodeURI(url),
      responseType: 'stream'
    })
      .then(function (response) {
        // console.log(response);
        if (response.status === 200) {
          
          // contentDisposition 中存储的是文件名信息。
          const contentDisposition = response.headers['content-disposition']
          // console.log("contentDisposition", contentDisposition);
          // 解决中文乱码问题
          const filename = decodeURI(contentDisposition.replace(/"|'/g, ' ').split(';')[1]?.split('=')[1]?.trim())

          const saveFile = path.join(dest, filename)

          fs.mkdirSync(path.dirname(saveFile), { recursive: true })

          response.data.pipe(fs.createWriteStream(saveFile));

          response.data.on('end', () => {
            setTimeout(() => {
              resolve(filename);
            }, 500)
          });
        } else {
          reject(new Error(`Request Failed,Status Code: ${response.status}`))
          // logger.error('doRequest error: ', `Request Failed,Status Code: ${response.status}`)
        }
      })
      .catch(function (error) {
        //   logger.error('download error: ', error.message)
        reject(error);
      });
      
  })
}

module.exports = {
  doRequest, download
}

// ;(async () => {
//   console.log(await download("https://acg.rip/t/241424.torrent", '/Users/shanke/Downloads/'));
// })()

